﻿using System;
using System.Collections.Generic;
using System.Text;
using WcfServiceBomberman.MatchMaking.Queues;
using BomberManServer.Utils;

namespace WcfServiceBomberman.MatchMaking
{
    public class MatchMaker : Context.Handler
    {
        // Queues
        // Solo
        // Duo
        // FFA
        Queue[] queues = new Queue[3];
        ConcurrentDoubleBufferedLinkedList<MatchMaking.Queueable>.Consumer buffer;
        List<uint> queued;  

        public MatchMaker()
        {
            queues[(int)MatchType.SOLO] = new Solo();
            queues[(int)MatchType.DUO] = new Duo();
            queues[(int)MatchType.FFA] = new FFA();

            queued = new List<uint>();

            buffer = context.players.consumer;
        }

        // thread loop
        public void start()
        {
            while (true)
            {
                read();
                compute();
                // write is in compute
                System.Threading.Thread.Sleep(0);
            }
        }

        private void read()
        {
            Queueable target;
            while (buffer.consume(out target))
                queues[(int)target.type].add(target.p) ;
        }

        private void compute()
        {
            foreach (Queue queue in queues)
                queue.fetch();
        }

        public bool isQueued(uint uid)
        {
            return queued.Contains(uid);
        }

        public void queue(uint uid)
        {
            queued.Add(uid);
        }

        public void unqueue(uint uid)
        {
            queued.Remove(uid);
        }
    }
}
